<template>
  <div class="appointment-list-container">
    <el-card class="appointment-card">
      <template #header>
        <div class="card-header">
          <span>预约列表</span>
          <div class="filter-form">
            <el-select v-model="filterForm.status" placeholder="预约状态" clearable>
              <el-option label="全部状态" value=""></el-option>
              <el-option label="待确认" value="pending"></el-option>
              <el-option label="已确认" value="confirmed"></el-option>
              <el-option label="已完成" value="completed"></el-option>
              <el-option label="已取消" value="canceled"></el-option>
            </el-select>
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD">
            </el-date-picker>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </div>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
        <el-skeleton style="margin-top: 20px" :rows="3" animated />
      </div>
      
      <div v-else-if="appointmentList.length === 0" class="empty-container">
        <el-empty description="暂无预约记录" />
      </div>
      
      <div v-else class="appointment-table-container">
        <el-table :data="appointmentList" style="width: 100%">
          <el-table-column prop="appointmentNo" label="预约号" width="120"></el-table-column>
          <el-table-column prop="appointmentType" label="预约类型" width="120">
            <template #default="scope">
              <el-tag :type="getAppointmentTypeTag(scope.row.appointmentType)">
                {{ getAppointmentTypeText(scope.row.appointmentType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="designerName" label="设计师"></el-table-column>
          <el-table-column prop="appointmentDate" label="预约日期" width="120"></el-table-column>
          <el-table-column prop="timeSlot" label="时间段" width="120"></el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
              <el-tag :type="getStatusTag(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewAppointment(scope.row)">
                查看
              </el-button>
              <el-button 
                v-if="['pending', 'confirmed'].includes(scope.row.status)"
                type="danger" 
                size="small" 
                @click="cancelAppointment(scope.row)">
                取消
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total">
          </el-pagination>
        </div>
      </div>
    </el-card>
    
    <!-- 预约详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="预约详情"
      width="50%">
      <div v-if="currentAppointment.id" class="appointment-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="预约号">{{ currentAppointment.appointmentNo }}</el-descriptions-item>
          <el-descriptions-item label="预约类型">
            <el-tag :type="getAppointmentTypeTag(currentAppointment.appointmentType)">
              {{ getAppointmentTypeText(currentAppointment.appointmentType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预约状态">
            <el-tag :type="getStatusTag(currentAppointment.status)">
              {{ getStatusText(currentAppointment.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预约日期">{{ currentAppointment.appointmentDate }}</el-descriptions-item>
          <el-descriptions-item label="时间段">{{ currentAppointment.timeSlot }}</el-descriptions-item>
          <el-descriptions-item label="设计师">{{ currentAppointment.designerName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentAppointment.phone }}</el-descriptions-item>
          <el-descriptions-item label="预约地址">{{ currentAppointment.address }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ currentAppointment.remark || '无' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentAppointment.createTime }}</el-descriptions-item>
          <el-descriptions-item v-if="currentAppointment.cancelReason" label="取消原因">
            {{ currentAppointment.cancelReason }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentAppointment.cancelTime" label="取消时间">
            {{ currentAppointment.cancelTime }}
          </el-descriptions-item>
        </el-descriptions>
        
        <el-divider content-position="center">预约进度</el-divider>
        
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in currentAppointment.activities"
            :key="index"
            :timestamp="activity.time"
            :type="getActivityType(activity.status)"
            :color="getActivityColor(activity.status)">
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="['pending', 'confirmed'].includes(currentAppointment.status)"
            type="danger" 
            @click="showCancelDialog">
            取消预约
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 取消预约对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消预约"
      width="30%">
      <div class="cancel-form">
        <p>您确定要取消该预约吗？</p>
        <el-form 
          ref="cancelFormRef"
          :model="cancelForm"
          :rules="cancelRules"
          label-width="80px">
          <el-form-item label="取消原因" prop="reason">
            <el-input 
              type="textarea" 
              v-model="cancelForm.reason" 
              :rows="3"
              placeholder="请输入取消原因">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAppointmentList, getAppointmentDetail, cancelAppointment } from '@/api/appointment'

export default {
  name: 'AppointmentList',
  setup() {
    const loading = ref(false)
    const appointmentList = ref([])
    const currentAppointment = ref({})
    const detailDialogVisible = ref(false)
    const cancelDialogVisible = ref(false)
    const cancelFormRef = ref(null)
    
    // 筛选表单
    const filterForm = reactive({
      status: '',
      dateRange: []
    })
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 取消表单
    const cancelForm = reactive({
      id: '',
      reason: ''
    })
    
    // 取消表单验证规则
    const cancelRules = {
      reason: [
        { required: true, message: '请输入取消原因', trigger: 'blur' },
        { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
      ]
    }
    
    // 获取预约列表
    const fetchAppointmentList = async () => {
      loading.value = true
      
      // 处理日期范围
      const startDate = filterForm.dateRange && filterForm.dateRange.length > 0 ? filterForm.dateRange[0] : ''
      const endDate = filterForm.dateRange && filterForm.dateRange.length > 0 ? filterForm.dateRange[1] : ''
      
      try {
        const params = {
          page: pagination.currentPage,
          pageSize: pagination.pageSize,
          status: filterForm.status,
          startDate,
          endDate
        }
        
        // 实际项目中应调用API
        // const res = await getAppointmentList(params)
        
        // 模拟API响应
        setTimeout(() => {
          const mockData = {
            total: 23,
            list: generateMockAppointments()
          }
          
          appointmentList.value = mockData.list
          pagination.total = mockData.total
          loading.value = false
        }, 800)
      } catch (error) {
        ElMessage.error('获取预约列表失败')
        loading.value = false
      }
    }
    
    // 生成模拟预约数据
    const generateMockAppointments = () => {
      const statuses = ['pending', 'confirmed', 'completed', 'canceled']
      const types = ['measurement', 'design', 'fitting', 'consultation']
      const timeSlots = ['上午 9:00-12:00', '下午 13:00-17:00', '晚上 18:00-20:00']
      
      const appointments = []
      for (let i = 1; i <= pagination.pageSize; i++) {
        const id = (pagination.currentPage - 1) * pagination.pageSize + i
        const status = statuses[Math.floor(Math.random() * statuses.length)]
        const type = types[Math.floor(Math.random() * types.length)]
        
        // 生成日期，近30天内
        const date = new Date()
        date.setDate(date.getDate() - Math.floor(Math.random() * 30))
        const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
        
        appointments.push({
          id,
          appointmentNo: `AP${new Date().getFullYear()}${String(id).padStart(6, '0')}`,
          appointmentType: type,
          designerName: `设计师${id % 5 + 1}`,
          appointmentDate: formattedDate,
          timeSlot: timeSlots[Math.floor(Math.random() * timeSlots.length)],
          status,
          phone: '138****' + String(1000 + id).slice(-4),
          address: '北京市朝阳区CBD商务中心',
          remark: Math.random() > 0.5 ? '需要带齐相关证件' : null,
          createTime: '2023-05-15 14:32:10',
          cancelReason: status === 'canceled' ? '个人原因，临时有事无法赴约' : null,
          cancelTime: status === 'canceled' ? '2023-05-16 10:25:30' : null,
          activities: generateActivities(status)
        })
      }
      
      // 应用筛选
      return appointments.filter(item => {
        // 状态筛选
        if (filterForm.status && item.status !== filterForm.status) {
          return false
        }
        
        // 日期范围筛选
        if (filterForm.dateRange && filterForm.dateRange.length === 2) {
          const appointmentDate = new Date(item.appointmentDate)
          const startDate = new Date(filterForm.dateRange[0])
          const endDate = new Date(filterForm.dateRange[1])
          endDate.setHours(23, 59, 59)
          
          if (appointmentDate < startDate || appointmentDate > endDate) {
            return false
          }
        }
        
        return true
      })
    }
    
    // 生成活动记录
    const generateActivities = (status) => {
      const activities = [
        {
          status: 'created',
          content: '创建预约',
          time: '2023-05-15 14:32:10'
        }
      ]
      
      if (['confirmed', 'completed', 'canceled'].includes(status)) {
        activities.push({
          status: 'confirmed',
          content: '预约已确认',
          time: '2023-05-15 15:10:25'
        })
      }
      
      if (status === 'completed') {
        activities.push({
          status: 'completed',
          content: '预约已完成',
          time: '2023-05-20 11:30:45'
        })
      }
      
      if (status === 'canceled') {
        activities.push({
          status: 'canceled',
          content: '预约已取消',
          time: '2023-05-16 10:25:30'
        })
      }
      
      return activities
    }
    
    // 查看预约详情
    const viewAppointment = async (appointment) => {
      try {
        // 实际项目中应调用API
        // const res = await getAppointmentDetail(appointment.id)
        
        // 模拟API响应
        setTimeout(() => {
          currentAppointment.value = appointment
          detailDialogVisible.value = true
        }, 300)
      } catch (error) {
        ElMessage.error('获取预约详情失败')
      }
    }
    
    // 显示取消预约对话框
    const cancelAppointment = (appointment) => {
      currentAppointment.value = appointment
      cancelForm.id = appointment.id
      cancelForm.reason = ''
      cancelDialogVisible.value = true
    }
    
    // 显示取消对话框
    const showCancelDialog = () => {
      cancelForm.id = currentAppointment.value.id
      cancelForm.reason = ''
      cancelDialogVisible.value = true
    }
    
    // 确认取消预约
    const confirmCancel = async () => {
      const valid = await cancelFormRef.value.validate().catch(() => false)
      if (!valid) return
      
      try {
        // 实际项目中应调用API
        // await cancelAppointment(cancelForm.id, cancelForm.reason)
        
        // 模拟API调用
        setTimeout(() => {
          // 更新本地数据
          const index = appointmentList.value.findIndex(item => item.id === cancelForm.id)
          if (index !== -1) {
            appointmentList.value[index].status = 'canceled'
            appointmentList.value[index].cancelReason = cancelForm.reason
            appointmentList.value[index].cancelTime = new Date().toLocaleString()
            appointmentList.value[index].activities.push({
              status: 'canceled',
              content: '预约已取消',
              time: new Date().toLocaleString()
            })
          }
          
          // 如果当前显示的是这个预约的详情，同步更新
          if (currentAppointment.value.id === cancelForm.id) {
            currentAppointment.value = appointmentList.value[index]
          }
          
          ElMessage.success('预约已取消')
          cancelDialogVisible.value = false
        }, 500)
      } catch (error) {
        ElMessage.error('取消预约失败')
      }
    }
    
    // 获取预约类型文本
    const getAppointmentTypeText = (type) => {
      const typeMap = {
        measurement: '量体',
        design: '设计咨询',
        fitting: '试衣',
        consultation: '通用咨询'
      }
      return typeMap[type] || type
    }
    
    // 获取预约类型标签类型
    const getAppointmentTypeTag = (type) => {
      const typeMap = {
        measurement: 'success',
        design: 'primary',
        fitting: 'warning',
        consultation: 'info'
      }
      return typeMap[type] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        pending: '待确认',
        confirmed: '已确认',
        completed: '已完成',
        canceled: '已取消'
      }
      return statusMap[status] || status
    }
    
    // 获取状态标签类型
    const getStatusTag = (status) => {
      const statusMap = {
        pending: 'warning',
        confirmed: 'success',
        completed: 'primary',
        canceled: 'info'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取活动类型
    const getActivityType = (status) => {
      const statusMap = {
        created: 'primary',
        confirmed: 'success',
        completed: 'success',
        canceled: 'warning'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取活动颜色
    const getActivityColor = (status) => {
      const statusMap = {
        created: '#409EFF',
        confirmed: '#67C23A',
        completed: '#67C23A',
        canceled: '#E6A23C'
      }
      return statusMap[status] || '#909399'
    }
    
    // 处理查询
    const handleSearch = () => {
      pagination.currentPage = 1
      fetchAppointmentList()
    }
    
    // 处理每页条数变化
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      fetchAppointmentList()
    }
    
    // 处理页码变化
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      fetchAppointmentList()
    }
    
    // 初始化
    onMounted(() => {
      fetchAppointmentList()
    })
    
    return {
      loading,
      appointmentList,
      currentAppointment,
      detailDialogVisible,
      cancelDialogVisible,
      cancelFormRef,
      filterForm,
      pagination,
      cancelForm,
      cancelRules,
      fetchAppointmentList,
      viewAppointment,
      cancelAppointment,
      showCancelDialog,
      confirmCancel,
      getAppointmentTypeText,
      getAppointmentTypeTag,
      getStatusText,
      getStatusTag,
      getActivityType,
      getActivityColor,
      handleSearch,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.appointment-list-container {
  padding: 20px;
}

.appointment-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.filter-form {
  display: flex;
  gap: 10px;
}

.loading-container,
.empty-container {
  min-height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.appointment-detail {
  max-width: 100%;
}

.cancel-form {
  padding: 10px;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-form {
    margin-top: 10px;
    width: 100%;
    flex-wrap: wrap;
  }
}
</style> 